﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using RStein.Posterous.API;
using System.Collections.Generic;

namespace RStein.PosterousReader.WP.Extensions
{
    public static class IPosterousApplicationExtensions
    {
        private static Dictionary<string,  IPosterousAccount> _cachedAccounts = new Dictionary<string, IPosterousAccount>();

       
        public static IPosterousAccount GetOrAddCachedPosterousAccount(this IPosterousApplication application,
                                                                       string userName,
                                                                       string userPassword)
        {

            checkApplicationNotNull(application);
            
            IPosterousAccount posterousAccount = GetCachedPosterousAccount(application, userName);;
            
            
             if (posterousAccount != null)
             {
                 return posterousAccount;
             }

            posterousAccount = application.GetPosterousAccount(userName, userPassword);

            _cachedAccounts.Add(userName, posterousAccount);

            return posterousAccount;
        }

        public static IPosterousAccount GetCachedPosterousAccount(this IPosterousApplication application,
                                                                       string userName
                                                                 )
        {

            IPosterousAccount posterousAccount = null;
            checkApplicationNotNull(application);

            if (_cachedAccounts.TryGetValue(userName, out posterousAccount))
            {
                return posterousAccount;
            }

            return null;
        }


        public static void RemoveCachedPosterousAccountForUserName(this IPosterousApplication application,
                                                                    string userName)
                                                           
        {

            _cachedAccounts.Remove(userName);
        }

        public static void RemoveAllCachedPosterousAccounts(this IPosterousApplication application)                                                                                                                   
        {            

            _cachedAccounts.Clear();
        }


        private static void checkApplicationNotNull(IPosterousApplication application)
        {
            if (application == null)
            {
                throw new ArgumentNullException("application");
            }
        }
    }
}
